#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app
from database import db
from models.user import User
from models.order import Order
from models.recharge import Recharge
from models.table import BilliardTable
from models.admin import Admin
from models.staff import Staff
from models.task import Task

def init_database():
    """初始化数据库"""
    with app.app_context():
        # 删除所有表
        print("正在删除现有表...")
        db.drop_all()
        
        # 创建所有表
        print("正在创建数据库表...")
        db.create_all()
        
        # 创建默认管理员
        if not Admin.query.filter_by(username='admin').first():
            admin = Admin(
                username='admin',
                password='admin123',
                name='系统管理员',
                email='admin@billiard.com'
            )
            db.session.add(admin)
        
        # 创建示例工作人员
        staff_list = [
            {
                'staff_no': 'S001',
                'username': 'waiter01',
                'password': '123456',
                'name': '张小明',
                'phone': '13800138001',
                'position': 'waiter',
                'department': '服务部'
            },
            {
                'staff_no': 'S002', 
                'username': 'cleaner01',
                'password': '123456',
                'name': '李小红',
                'phone': '13800138002',
                'position': 'cleaner',
                'department': '清洁部'
            }
        ]
        
        for staff_data in staff_list:
            if not Staff.query.filter_by(username=staff_data['username']).first():
                staff = Staff(**staff_data)
                db.session.add(staff)
        
        # 创建示例台球桌
        tables = [
            {'table_no': 'T001', 'table_name': '1号九球桌', 'table_type': 'nine_ball', 'hourly_rate': 60.00},
            {'table_no': 'T002', 'table_name': '2号斯诺克桌', 'table_type': 'snooker', 'hourly_rate': 80.00},
            {'table_no': 'T003', 'table_name': '3号中式八球桌', 'table_type': 'chinese_eight', 'hourly_rate': 50.00}
        ]
        
        for table_data in tables:
            if not BilliardTable.query.filter_by(table_no=table_data['table_no']).first():
                table = BilliardTable(**table_data)
                db.session.add(table)
        
        db.session.commit()
        
        print("数据库初始化完成！")
        print("管理员账号：admin / admin123")
        print("工作人员账号：")
        print("  - waiter01 / 123456 (服务员张小明)")
        print("  - cleaner01 / 123456 (清洁员李小红)")

if __name__ == '__main__':
    init_database()